package goldeneagle.com.user.servlet;

import goldeneagle.com.entity.User;
import goldeneagle.com.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
 *Created by GHW
 *Description:用户登录
 *2019/11/12 16:04
 */
@WebServlet(value = "/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收前端信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userType = request.getParameter("userType");
        //调用service方法进行判断
        UserService findUserService = new UserService();
        if (findUserService.FindUserByUsername(username) != null) {
            //判断是管理员还是用户 成功返回用户类型
            User user = findUserService.FindUserByUsername(username);
            if (user.getPassword().equals(password) && user.getUserType().equals(userType)) {
                HttpSession session = request.getSession();
                session.setAttribute("userOrAdmin", user);
                if (userType.equals("admin")) { //管理员跳转到管理员首页
                    response.getWriter().write("admin");
                    response.getWriter().write("userID:" + user.getId());
                    response.getWriter().write("<script>alert('登陆成功');</script>");
                    request.getRequestDispatcher("admin.jsp").forward(request, response);
                } else if (userType.equals("user")) {//用户跳转到用户首页
                    response.getWriter().write("user");
                    response.getWriter().write("userID:" + user.getId());
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                }
                //否则返回失败
            } else {
                response.getWriter().write("failed:用户名密码或者用户类型错误");
            }
        } else {
            response.getWriter().write("failed:没有此用户");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
